/* eslint-disable default-case */
import {
  dimissionList,
  dimssionDetail,
  contactAdd,
  dimssionDetailInfor,
  getDimissionHistory,
  contactAddAgin,
  signPro,
  getProList,
  insertProbFdbk,
  getProBaseList,
  cancelProbFlag,
  uploadFile,
} from '@/services/careermange';
import router from 'umi/router';
import { message } from 'antd';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'dimission';

export default {
  namespace,
  state: {
    formFieldsValue: {},
    expandForm: false,
    activeKey: '1',
    data: {
      list: [],
      pagination: {
        current: 1,
        // pageSizes: 10,
        pageSize: 10,
        total: 0,
      },
    },
    detail: {
      empDimiContHisList: [],
      empDimission: {},
      ordHdlRemarkDtos: [],
    },
    pageOrdBys: [{ property: null, ordBy: null }],
    detailInfor: {
      empDimiContHisList: [],
      empDimission: {},
      ordHdlRemarkDtos: [],
      rsgnDets: [],
    },
    dimHistory: [],
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proBaseList: {},
    proFbList: [],
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/esApi/empDimission/downloadExcelErrData', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
  },

  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(dimissionList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 开始联系
    *getDimission({ payload }, { call, put }) {
      const response = yield call(dimssionDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 详情
    *getDimissionInfor({ payload }, { call, put }) {
      const response = yield call(dimssionDetailInfor, payload);
      if (response.success) {
        yield put({
          type: 'getDetailInfor',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 开始联系
    contact:[
      function*({ payload }, { call }) {
        const response = yield call(contactAdd, payload);
        if (response.success) {
          router.push(`/careermanage/dimission/index`);
        } else {
          message.warning(response.message || '服务端错误');
        }
      },
      { type:'throttle', ms:10000 }
    ],
    // 再次联系
    contactAgin:[
      function*({ payload }, { call }) {
        const response = yield call(contactAddAgin, payload);
        if (response.success) {
          router.push(`/careermanage/dimission/index`);
        } else {
          message.warning(response.message || '服务端错误');
        }
      },
      { type:'throttle', ms:10000 }
    ],
    // 获取历史
    *getHistory({ payload }, { call, put }) {
      const response = yield call(getDimissionHistory, payload);
      if (response.success) {
        yield put({
          type: 'getDimissionHistory',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 标记问题人员
    *signPro({ payload, callback }, { call }) {
      const response = yield call(signPro, payload);
      if (callback) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getProList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 社保服务办理问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(insertProbFdbk, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 获取问题人员详情
    *fetchProBaseList({ payload }, { call, put }) {
      const response = yield call(getProBaseList, payload);
      if (response.success) {
        yield put({
          type: 'getProBaseList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 反馈并取消
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(cancelProbFlag, payload);
      if (callback) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 获取进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFile, payload);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      {type:'throttle',ms : 10000 }
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.dimission);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 批量进度
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: {
            total: data.totalCount,
            current: currentPage,
            pageSize,
            // pageSize: pageSizes,
          },
        },
      };
    },
    // 获取详情数据
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    // 获取开始联系详情
    getDetailInfor(state, { payload }) {
      const newArr = payload;
      Object.keys(newArr).forEach(key => {
        if (key === 'rsgnDets') {
          newArr[key] = Array.isArray(newArr[key]) ? newArr[key] : [];
        }
      });
      return {
        ...state,
        detailInfor: newArr,
      };
    },
    // 获取历史记录
    getDimissionHistory(state, { payload }) {
      return {
        ...state,
        dimHistory: payload,
      };
    },
    // 问题人员列表
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proListData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员基本信息
    getProBaseList(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbks,
      };
    },
    // 更新数据
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
